<template>
  <div class="login">
    <!-- 光效元素 -->
    <div class="light-effect"></div>
    <div class="light-effect"></div>
    <div class="light-effect"></div>
    
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="logo-container">
        <img src="/logo.png" alt="Logo" class="login-logo" />
      </div>
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="账号"
        >
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <div v-if="codeLoading" class="code-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <img 
            v-else-if="codeUrl" 
            :src="codeUrl" 
            @click="getCode" 
            class="login-code-img"
            title="点击刷新验证码"
          />
          <div v-else class="code-error" @click="getCode">
            <el-icon><RefreshRight /></el-icon>
            <span>点击重试</span>
          </div>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width:100%;"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->

  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'
import settings from '@/settings'
import { Loading, RefreshRight } from '@element-plus/icons-vue'

const title = settings.title
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
})

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
}

const codeUrl = ref("")
const loading = ref(false)
const codeLoading = ref(false) // 验证码加载状态
// 验证码开关 - 初始值设为false，等待后端接口返回
const captchaEnabled = ref(false)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 })
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        router.push({ path: redirect.value || "/", query: otherQueryParams })
      }).catch(() => {
        loading.value = false
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}

function getCode() {
  codeLoading.value = true // 开始加载
  
  getCodeImg().then(res => {
    console.log('验证码接口返回:', res) // 添加调试信息
    
    // 检查接口返回的数据结构
    if (res && typeof res === 'object') {
      // 设置验证码开关状态
      captchaEnabled.value = res.captchaEnabled !== false // 默认启用，除非明确返回false
      
      if (captchaEnabled.value && res.img) {
        codeUrl.value = "data:image/gif;base64," + res.img
        loginForm.value.uuid = res.uuid
        console.log('验证码已加载，UUID:', res.uuid)
      } else {
        console.log('验证码被禁用或图片数据为空')
        codeUrl.value = ""
      }
    } else {
      console.error('验证码接口返回数据格式异常:', res)
      // 如果接口返回异常，默认启用验证码但显示错误提示
      captchaEnabled.value = true
      codeUrl.value = ""
    }
  }).catch(error => {
    console.error('获取验证码失败:', error)
    // 网络错误时的处理
    captchaEnabled.value = true
    codeUrl.value = ""
    proxy.$modal.msgError("获取验证码失败，请检查网络连接")
  }).finally(() => {
    codeLoading.value = false // 结束加载
  })
}

function getCookie() {
  const username = Cookies.get("username")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: "", // 不自动填入密码，提高安全性
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

getCode()
getCookie()
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #ffffff;
  position: relative;
  overflow: hidden;
  
  // 光效动画背景
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(74, 144, 226, 0.15) 0%, rgba(74, 144, 226, 0.05) 40%, transparent 70%);
    animation: rotate 20s linear infinite;
    z-index: 0;
  }
  
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      radial-gradient(circle at 20% 80%, rgba(74, 144, 226, 0.12) 0%, rgba(74, 144, 226, 0.03) 30%, transparent 60%),
      radial-gradient(circle at 80% 20%, rgba(16, 185, 129, 0.12) 0%, rgba(16, 185, 129, 0.03) 30%, transparent 60%),
      radial-gradient(circle at 40% 40%, rgba(139, 92, 246, 0.10) 0%, rgba(139, 92, 246, 0.02) 30%, transparent 60%),
      radial-gradient(circle at 60% 70%, rgba(236, 72, 153, 0.08) 0%, transparent 50%);
    animation: float 6s ease-in-out infinite;
    z-index: 0;
  }
  
  // 额外的脉冲光效
  .light-effect {
    position: absolute;
    width: 300px;
    height: 300px;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(74, 144, 226, 0.1) 0%, transparent 70%);
    animation: pulse 4s ease-in-out infinite;
    z-index: 0;
    
    &:nth-child(1) {
      top: 10%;
      left: 15%;
      animation-delay: 0s;
    }
    
    &:nth-child(2) {
      top: 60%;
      right: 10%;
      background: radial-gradient(circle, rgba(16, 185, 129, 0.08) 0%, transparent 70%);
      animation-delay: 1.5s;
    }
    
    &:nth-child(3) {
      bottom: 20%;
      left: 50%;
      transform: translateX(-50%);
      background: radial-gradient(circle, rgba(139, 92, 246, 0.06) 0%, transparent 70%);
      animation-delay: 3s;
    }
  }
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes float {
  0%, 100% { 
    transform: translateY(0px) scale(1);
    opacity: 0.8;
  }
  33% { 
    transform: translateY(-15px) scale(1.02);
    opacity: 1;
  }
  66% { 
    transform: translateY(-25px) scale(1.08);
    opacity: 0.9;
  }
}

@keyframes pulse {
  0%, 100% { 
    transform: scale(1);
    opacity: 0.6;
  }
  50% { 
    transform: scale(1.1);
    opacity: 0.8;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.logo-container {
  text-align: center;
  margin-bottom: 20px;
  
  .login-logo {
    width: 80px;
    height: 80px;
    object-fit: contain;
    filter: drop-shadow(0 4px 8px rgba(0,0,0,0.1));
    transition: all 0.3s ease;
    
    &:hover {
      filter: drop-shadow(0 6px 12px rgba(0,0,0,0.15));
    }
  }
}

.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 2px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.login-form {
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  width: 420px;
  padding: 40px 35px 25px 35px;
  box-shadow: 
    0 20px 40px rgba(0, 0, 0, 0.1),
    0 15px 25px rgba(0, 0, 0, 0.05),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 2;
  animation: fadeInUp 0.8s ease-out;
  transition: all 0.3s ease;
  
  
  .el-form-item {
    margin-bottom: 25px;
    
    .el-input {
      height: 50px;
      border-radius: 12px;
      overflow: hidden;
      transition: all 0.3s ease;
      
      input {
        height: 50px;
        border: 2px solid rgba(103, 126, 234, 0.1);
        border-radius: 12px;
        padding-left: 50px;
        font-size: 16px;
        background: rgba(255, 255, 255, 0.8);
        transition: all 0.3s ease;
        
        &:focus {
          border-color: #667eea;
          background: rgba(255, 255, 255, 1);
          box-shadow: 0 0 0 3px rgba(103, 126, 234, 0.1);
        }
        
        &::placeholder {
          color: #a0a0a0;
          font-size: 14px;
        }
      }
    }
  }
  
  .input-icon {
    height: 39px;
    width: 16px;
    margin-left: 5px;
    color: #667eea;
    transition: all 0.3s ease;
  }
  
  .el-checkbox {
    .el-checkbox__label {
      color: #666;
      font-size: 14px;
    }
    
    .el-checkbox__input.is-checked .el-checkbox__inner {
      background-color: #667eea;
      border-color: #667eea;
    }
  }
  
  .el-button {
    height: 50px;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 1px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    box-shadow: 0 8px 20px rgba(103, 126, 234, 0.3);
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 12px 25px rgba(103, 126, 234, 0.4);
    }
  }
  
  .link-type {
    color: #667eea;
    text-decoration: none;
    font-size: 14px;
    transition: all 0.3s ease;
    
    &:hover {
      color: #764ba2;
      text-decoration: underline;
    }
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 50px;
  float: right;
  
  img {
    cursor: pointer;
    vertical-align: middle;
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.05);
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #666;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  z-index: 1;
}

.login-code-img {
  height: 50px;
  padding-left: 12px;
  border-radius: 8px;
  border: 2px solid rgba(103, 126, 234, 0.1);
}

// 验证码加载状态样式
.code-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  width: 100%;
  background: rgba(103, 126, 234, 0.05);
  border: 2px solid rgba(103, 126, 234, 0.1);
  border-radius: 8px;
  color: #667eea;
  font-size: 12px;
  margin-left: 12px;
  
  .el-icon {
    margin-right: 4px;
    font-size: 14px;
  }
}

// 验证码错误状态样式
.code-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  width: 100%;
  background: rgba(245, 108, 108, 0.05);
  border: 2px solid rgba(245, 108, 108, 0.2);
  border-radius: 8px;
  color: #f56c6c;
  font-size: 12px;
  margin-left: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background: rgba(245, 108, 108, 0.1);
    border-color: rgba(245, 108, 108, 0.3);
  }
  
  .el-icon {
    margin-right: 4px;
    font-size: 14px;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-form {
    width: 90%;
    margin: 0 20px;
    padding: 30px 25px 20px 25px;
  }
  
  .title {
    font-size: 24px;
    margin-bottom: 30px;
  }
}
</style>
